<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/28
 * Time: 17:51
 */

//Log::write($log, $extra_info, $file_name);
class Log
{
    public static $max_size = 2;
    public static $logfile = 'curr.log';
    public static $file_path;
    public static $dir;
    public static $bakname;
    public static $append = 1;

    public static function write( $log="/*******************/", $extra_info = '', $file_name = '' )
    {
        $content = "\r\n" . date( 'Y-m-d H:i:s' ) . "　" . $extra_info . "\r\n　     　　";
        if ( is_array( $log ) ) {
            $arr_str = '';
            foreach ( $log as $k => $v ) {
                $arr_str .= $k . '=>' . $v . "　";
            }
            $log = $arr_str;
        }
        if(empty($log)){
            $log="/****************************/";
        }
        $content .= $log . "\r\n";
        if ( !self::_isDir() ) {
            exit( self::LOGPATH . '不存在且没有权限创建' );
        }
        $log = self::_isBak( self::$file_path );
        $fp = fopen( $log, self::$append ? 'a+b' : 'w+' );
        fwrite( $fp, $content );
        fclose( $fp );
    }

    //备份日志
    public static function _bak()
    {
        $bak = self::$dir . date( 'Y_m_d_H' ) . '.bak';
        return rename( self::$file_path, $bak );
    }

    public static function _isBak( $log_path )
    {
        $log = $log_path;
        if ( !file_exists( $log ) ) {
            touch( $log );
            return $log;
        }
        $size = filesize( $log );
        if ( $size <= 1024 * self::$max_size ) {
            return $log;
        }
        if ( !self::_bak() ) {
            return $log;
        } else {
            touch( $log );

            return $log;
        }
    }

    public static function _isDir()
    {
        if ( !self::$dir ) {
            $log_dir = dirname(dirname( __FILE__ )).'/logs';
        }else{
            $log_dir=self::$dir;
        }
        if ( !is_dir( $log_dir ) ) {
            if ( !mkdir( $log_dir, 0755, true ) ) {
                return false;
            }
        }
        self::$dir = $log_dir . '/';
        self::$file_path = $log_dir . '/' . self::$logfile;
        return true;
    }
}